<template>
  <q-layout view="hHh LpR fFf">
    <q-header class="bg-transparent text-white">
      <q-toolbar class="q-px-none">
        <q-toolbar-title>
          <with-logo-button @click="toggleLeftDrawer"></with-logo-button>
          <div
            class="rectangle"
            :style="{
              background: currentColor.innerColor,
              opacity: leftDrawerOpen ? '0.9' : '0',
            }"
          ></div>
          <template
            v-for="(item, idx) of mainActionButtons"
            :key="item.name + idx"
          >
            <MainActionsButton
              :item="item"
              :bottom-line-color="currentColor"
              :current="idx === currentTab"
              :mini="($q.screen.lt.lg && idx !== currentTab) || $q.screen.lt.md"
              :style="idx > 0 ? 'margin-left: -9px' : 'margin-left: 4px'"
              @click="setCurrentTab(item, idx)"
            ></MainActionsButton>
          </template>
          <SpaceWithBottomLine
            :item="currentColor"
            :color="currentColor"
            v-if="$q.screen.gt.md"
            style="margin-left: -9px"
          ></SpaceWithBottomLine>
          <template
            v-for="(item, idx) of leftGroupButtons"
            :key="item.name + idx"
          >
            <HeaderButton
              :item="item"
              :color="currentColor"
              :last="leftGroupButtons.length === idx + 1"
              style="margin-left: -9px"
              v-if="$q.screen.gt.xs"
              @click="setCurrentButton(item, idx)"
            ></HeaderButton>
          </template>
        </q-toolbar-title>
        <template
          v-for="(item, idx) of rightGroupButtons"
          :key="item.name + idx"
        >
          <HeaderButton
            :item="item"
            :color="usernameColor"
            :last="rightGroupButtons.length === idx + 1"
            :style="idx > 0 ? 'margin-left: -9px' : 'margin-left: 4px'"
            v-if="$q.screen.gt.xs"
          ></HeaderButton>
        </template>
        <UsernameButton
          v-if="isLoggedIn"
          style="margin-left: 5px"
          :item="usernameButton"
          :color="usernameColor"
          :mini="$q.screen.lt.md"
          @click="toggleRightDrawer"
        ></UsernameButton>
        <UsernameButton
          v-else
          style="margin-left: 5px"
          :item="{
            name: 'Войти',
            icon: 'userIcon.svg',
            tooltip: 'Нажмите для входа',
          }"
          :color="usernameColor"
          :mini="$q.screen.lt.md"
          @click="showLoginForm = true"
        ></UsernameButton>
      </q-toolbar>
    </q-header>

    <q-drawer
      v-model="leftDrawerOpen"
      side="left"
      behavior="desktop"
      :width="48"
      class="left-drawer"
      :style="{ background: currentColor.innerColor }"
    >
      <q-scroll-area
        :style="`height: calc(100vh - 54px - ${
          leftMenuTopGroupButtons.length * 48
        }px - ${leftMenuBottomGroupButtons.length * 5 + 5}px )`"
      >
        <q-list class="flex col" style="gap: 4px">
          <template
            v-for="(item, idx) of leftMenuTopGroupButtons"
            :key="item.name + idx"
          >
            <LeftMenuButton :item="item" :color="currentColor"></LeftMenuButton>
          </template>
        </q-list>
      </q-scroll-area>
      <q-list class="flex col" style="gap: 4px">
        <template
          v-for="(item, idx) of leftMenuBottomGroupButtons"
          :key="item.name + idx"
        >
          <LeftMenuButton :item="item" :color="currentColor"></LeftMenuButton>
        </template>
      </q-list>
    </q-drawer>

    <q-drawer
      v-model="rightDrawerOpen"
      side="right"
      :width="242"
      overlay
      behavior="desktop"
      class="right-drawer"
      :style="{ background: currentColor.innerColor }"
    >
      <q-list class="text-white right-drawer-list">
        <template
          v-for="(item, idx) of leftGroupButtons"
          :key="item.name + idx"
        >
          <RightMenuButton :item="item" :color="currentColor"></RightMenuButton>

          <template
            v-for="(item1, idx) of item.subbuttons"
            :key="item1.name + idx"
          >
            <RightMenuButton
              :item="item1"
              :color="currentColor"
            ></RightMenuButton>
          </template>
        </template>
      </q-list>
      <q-separator />

      <q-list class="text-white right-drawer-list">
        <template
          v-for="(item, idx) of rightGroupButtons"
          :key="item.name + idx"
        >
          <RightMenuButton
            :item="item"
            :color="usernameColor"
          ></RightMenuButton>
        </template>
      </q-list>
      <q-list class="text-white right-drawer-list">
        <RightMenuButton
          v-if="isLoggedIn"
          :item="{
            name: 'Выход',
            icon: 'logout',
            tooltip: 'Выход',
            action: logoutButton,
          }"
          :color="usernameColor"
        ></RightMenuButton>
        <RightMenuButton
          v-else
          :item="{
            name: 'Войти',
            icon: 'simpleCircleIcon.svg',
            tooltip: 'Нажмите для входа',
            action: () => ((showLoginForm = true), (rightDrawerOpen = false)),
          }"
          :color="usernameColor"
        ></RightMenuButton>
      </q-list>
    </q-drawer>

    <q-page-container class="page-container-background flex flex-center">
      <div class="flex justify-center container-wrap">
        <router-view class="" style="flex: 1 0 auto" />
        <BannersBlock
          v-if="!(['/'].includes($route.path) && !isLoggedIn)"
        ></BannersBlock>
      </div>
    </q-page-container>
    <!-- <CallBackButton /> -->
  </q-layout>
  <q-dialog v-model="showLoginForm" persistent>
    <sign-in-dialog></sign-in-dialog>
  </q-dialog>
</template>

<script>
import { ref } from "vue";
import WithLogoButton from "../components/buttons/WithLogoButton.vue";
import UsernameButton from "../components/buttons/UsernameButton.vue";
import MainActionsButton from "../components/buttons/MainActionsButton.vue";
import HeaderButton from "src/components/buttons/HeaderButton.vue";
import SpaceWithBottomLine from "../components/buttons/SpaceWithBottomLine.vue";
import LeftMenuButton from "src/components/buttons/LeftMenuButton.vue";
import RightMenuButton from "src/components/buttons/RightMenuButton.vue";
import { useAuthStore } from "src/stores/auth";
import { mapState, mapWritableState, mapActions } from "pinia";
import SignInDialog from "src/components/signInDialog.vue";
import { useUiStore } from "src/stores/UI";
import { sendYMgoal } from "src/utils/yandex_metrika_utils";
import BannersBlock from "../components/banners/BannersBlock.vue";
import meta from "src/utils/meta";
import { createMetaMixin } from "quasar";
import { QSpinnerGears } from "quasar";

// import CallBackButton from "components/callBackButton";

export default {
  // components: { CallBackButton },
  setup() {
    const mainActionButtons = ref([
      {
        name: "Знания",
        innerColor: "#5F8CEA",
        outerColor: "#6666FF",
        color: "blue",
        icon: "iconKnowledge.svg",
        tooltip: "Знания",
        action: "/",
        buttons: [
          {
            name: "Стартовая страница",
            icon: "rocket",
            tooltip: "Стартовая страница",
            action: "/",
            subbuttons: [
              {
                name: "Информация",
                icon: "iconInfo.svg",
                tooltip: "Информация",
                action: "/",
              },
              {
                name: "Как помочь",
                icon: "iconTeknokomo.svg",
                tooltip: "Как помочь",
                action: "/join",
              },
              {
                name: "MMORPG",
                icon: "iconMetaUniverses.svg",
                tooltip: "MMORPG",
                action: "/mmorpg",
              },
              // {
              //   name: "История изменений",
              //   icon: "iconChangelog.svg",
              //   tooltip: "История изменений",
              //   action: "/changelog",
              // },
              {
                name: "Текнокомо",
                icon: "iconRoadmap.svg",
                tooltip: "Текнокомо",
                action: "/teknokomo",
              },
              {
                name: "Омская лицензия",
                icon: "iconOL.svg",
                tooltip: "Омская лицензия",
                action: "/ol",
              },
              {
                name: "Награды",
                icon: "iconAwards.svg",
                tooltip: "Награды",
                action: "/premio",
              },
            ],
          },
        ],
      },
      {
        name: "Кибергосплан",
        innerColor: "#006868",
        outerColor: "#004F4F",
        color: "green",
        icon: "iconActions.svg",
        tooltip: "Кибергосплан",
        action: "/gosplan",

        buttons: [
          {
            name: "Стартовая страница",
            icon: "rocket",
            tooltip: "Стартовая страница",
            action: "/",
            subbuttons: [
              {
                name: "Информация",
                icon: "iconInfo.svg",
                tooltip: "Информация",
                action: "/gosplan",
              },
            ],
          },
        ],
      },
      {
        name: "Метавселенные",
        innerColor: "#502542",
        outerColor: "#340F28",
        color: "red",
        icon: "iconUniverses.svg",
        tooltip: "Метавселенные",
        action: "/metaverses",

        buttons: [
          {
            name: "Стартовая страница",
            icon: "rocket",
            tooltip: "Стартовая страница",
            action: "/",
            subbuttons: [
              {
                name: "Информация",
                icon: "iconInfo.svg",
                tooltip: "Информация",
                action: "/metaverses",
              },
              {
                name: "Гипервселенная",
                icon: "iconHyperUniverse.svg",
                tooltip: "Гипервселенная",
                action: "/hyperuniverse",
              },
            ],
          },
        ],
      },
    ]);
    const usernameColor = ref({
      innerColor: "#8282BF",
      outerColor: "#4A4AFF",
      color: "bluegray",
    });
    let currentTab = ref(0);
    let currentButton = ref(0);

    const rightGroupButtonsSet = ref([
      {
        name: "Профиль",
        icon: "psychology",
        tooltip: "Профиль",
        action: "/profile",
        authOnly: true,
      },
      // {
      //   name: "Button2",
      //   icon: "simpleCircleIcon.svg",
      //   tooltip: "Button2",
      // },
      // {
      //   name: "Button3",
      //   icon: "simpleCircleIcon.svg",
      //   tooltip: "Button3",
      // },
    ]);

    const leftMenuBottomGroupButtons = ref([
      // {
      //   name: "Button1",
      //   icon: "simpleCircleIcon.svg",
      //   tooltip: "Button1",
      // },
      // {
      //   name: "Button2",
      //   icon: "simpleCircleIcon.svg",
      //   tooltip: "Button2",
      // },
    ]);
    const rightDrawerOpen = ref(false);
    return {
      rightDrawerOpen,
      toggleRightDrawer() {
        rightDrawerOpen.value = !rightDrawerOpen.value;
      },
      mainActionButtons,
      usernameColor,

      rightGroupButtonsSet,

      leftMenuBottomGroupButtons,
      currentTab,
      currentButton,
    };
  },
  data() {
    return {
      confirm: true,
      acceptCookies: false,
    };
  },
  mixins: [
    createMetaMixin(function () {
      return meta(this.metaTags);
    }),
  ],
  components: {
    WithLogoButton,
    UsernameButton,
    MainActionsButton,
    HeaderButton,
    SpaceWithBottomLine,
    LeftMenuButton,
    RightMenuButton,
    SignInDialog,
    BannersBlock,
    // CallBackButton,
  },
  methods: {
    ...mapActions(useAuthStore, ["getLocalStorage"]),
    ...mapActions(useAuthStore, ["getMe"]),
    ...mapActions(useAuthStore, ["logout"]),
    ...mapActions(useUiStore, ["getLocalStoredUi", "setLocalStoredUi"]),
    toggleLeftDrawer() {
      this.leftDrawerOpen = !this.leftDrawerOpen;
    },
    setCurrentTab(item, index) {
      const { innerColor, outerColor, color } = item;
      // this.currentColor = { innerColor, outerColor, color };
      this.currentTab = index;
    },
    setCurrentButton(item, index) {
      this.currentButton = index;
    },
    logoutButton() {
      this.rightDrawerOpen = false;
      this.logout()
        .then(() => {
          sendYMgoal(this.$route.path, "logout", "button");
          this.$router.push("/");
        })
        .catch(() => {});
    },
  },
  computed: {
    ...mapState(useAuthStore, ["user"]),
    ...mapState(useAuthStore, { name: "getUserName" }),
    ...mapState(useAuthStore, { email: "getUserEmail" }),
    ...mapState(useAuthStore, ["isLoggedIn"]),
    ...mapWritableState(useUiStore, ["showLoginForm"]),
    ...mapState(useUiStore, ["localStoredUi"]),

    title: function () {
      return this.$route?.meta?.pageName;
    },
    metaTags() {
      return {
        title: this.title,
        description: `Погрузитесь через РВМ Универсо в гипервселенную — бесконечное пространство исследований, цифровизации и социального взаимодействия в метавселенных. Функционал Общественного КиберГосплана поможет управлять вашими проектами и организациями, объединиться в рамках Омского Международного Плана, создавать в любой точке мира новые Народные предприятия, Профсоюзы, Советы и любые проекты по интересам.`,
        keywords: `гипервселенная, метавселенные, госплан, кибергосплан, проекты, народные, предприятия, профсоюзы, советы, холсты, карточки, игры, работа`,
        url: process.env.APP_HOST + this.$route.path,
        image: "",
        robots: "",
      };
    },
    usernameButton: function () {
      return {
        name: this.name,
        icon: "userIcon.svg",
        tooltip: this.email,
      };
    },
    leftDrawerOpen: {
      get: function () {
        return this.localStoredUi?.leftDrawerOpen ?? true;
      },
      set: function (payload) {
        this.setLocalStoredUi({ leftDrawerOpen: payload });
      },
    },
    leftGroupButtons() {
      return this.mainActionButtons[this.currentTab]?.buttons ?? [];
    },
    leftMenuTopGroupButtons() {
      return (
        this.mainActionButtons[this.currentTab]?.buttons[this.currentButton]
          .subbuttons ?? []
      );
    },
    rightGroupButtons() {
      return this.rightGroupButtonsSet.filter((item) => {
        if (item.authOnly && this.isLoggedIn) {
          return true;
        }
        if (!item.authOnly) {
          return true;
        }
        return false;
      });
    },
    currentColor() {
      const { innerColor, outerColor, color } =
        this.mainActionButtons[this.currentTab];
      return { innerColor, outerColor, color };
    },
  },
  mounted() {
    this.getLocalStoredUi();
    this.getLocalStorage()
      .then(() => this.getMe())
      .catch(() => {
        if (this.$route.meta.requiresAuth) {
          this.$router.push("/");
        }
      });

    if (!this.localStoredUi?.acceptCookies) {
      setTimeout(() => {
        this.$q.notify({
          //progress: true,
          message: `<div style='font-size:1.2rem'><p><strong>Мы используем файлы cookies.</strong></p>
          <p>
Чтобы улучшить работу сайта и предоставить вам больше возможностей.</p></div> `,
          color: "positive",
          spinner: QSpinnerGears,
          group: false,

          multiLine: true,
          timeout: 0,
          html: true,
          actions: [
            {
              label: "Согласен",
              color: "white",
              handler: () => {
                this.setLocalStoredUi({ acceptCookies: true });
              },
            },
          ],
        });
      }, 2000);
    }
  },
  watch: {
    "$route.path": {
      handler(cur, old) {
        if (cur) {
          switch (cur) {
            case "/":
              this.currentTab = 0;
              break;
            case "/actions":
              this.currentTab = 1;
              break;
            case "/universes":
              this.currentTab = 2;
              break;
            case "/hyperuniverse":
              this.currentTab = 2;
              break;
            default:
              this.currentTab = 0;
              break;
          }
        }
      },
      immediate: true,
    },
  },
};
</script>
<style>
.page-container-background {
  background-image: url(~assets/background2.jpg);
  background-color: #cccccc;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: center;
  background-size: cover;
  z-index: 0;
  min-height: 100vh;
}
.page-container-background:after {
  content: "";
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
}
.rectangle {
  height: 18px;
  width: 18px;
  position: absolute;
  top: 51px;
  left: 50px;
  transition: all 1s;
  transform: translate(-50%, -50%) rotate(45deg);
  user-select: none;
}
.left-drawer {
  opacity: 0.9;
  margin-top: 3px;
  height: calc(100vh - 53px) !important;
  clip-path: polygon(0 0, calc(100% - 13px) 0, 100% 13px, 100% 100%, 0 100%);
}
.right-drawer {
  opacity: 0.97;
  margin-top: 3px;
  height: calc(100vh - 53px) !important;
  clip-path: polygon(13px 0, 100% 0, 100% 100%, 0 100%, 0 13px);
}
.right-drawer-list {
  gap: 5px;
  display: grid;
  padding: 10px;
}
.q-drawer--left,
.q-drawer--right {
  background-color: unset;
}
.container-wrap {
  flex-wrap: nowrap;
  min-height: calc(100vh - 50px);
  width: 100%;
}
@media (max-width: 1250px) {
  .container-wrap {
    flex-wrap: wrap;
  }
}
.q-notification__actions > button > span > span.block {
  font-size: 1.2rem;
}
</style>
